package com.zyl.pagergallerymoredemo_java.adapter;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.zyl.pagergallerymoredemo_java.R;
import com.zyl.pagergallerymoredemo_java.pojo.Pixabay;
import com.zyl.pagergallerymoredemo_java.viewModel.GalleryViewModel;

import java.util.ArrayList;

import io.supercharge.shimmerlayout.ShimmerLayout;

public class GalleryAdapter extends ListAdapter<Pixabay.PhotoItem, RecyclerView.ViewHolder> {

    public static final String PHOTO_LIST = "photo_list";
    public static final String PHOTO_POSITION = "photo_position";

    public int footerViewStatus = 0;
    private static final int NORMAL_VIEW_TYPE = 0;
    private static final int FOOTER_VIEW_TYPE = 1;
    private GalleryViewModel galleryViewModel;

    public GalleryAdapter(GalleryViewModel galleryViewModel) {
        super(new DiffUtil.ItemCallback<Pixabay.PhotoItem>() {
            @Override
            public boolean areItemsTheSame(@NonNull Pixabay.PhotoItem oldItem, @NonNull Pixabay.PhotoItem newItem) {
                return oldItem.getPhotoId() == newItem.getPhotoId();
            }

            @Override
            public boolean areContentsTheSame(@NonNull Pixabay.PhotoItem oldItem, @NonNull Pixabay.PhotoItem newItem) {
                return oldItem.getFullUrl().equals(newItem.getFullUrl())
                        && oldItem.getPreviewUrl().equals(newItem.getPreviewUrl());
            }
        });
        this.galleryViewModel = galleryViewModel;
    }

    @Override
    public int getItemCount() {
        return super.getItemCount() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return FOOTER_VIEW_TYPE;
        } else {
            return NORMAL_VIEW_TYPE;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == NORMAL_VIEW_TYPE) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_gallery, parent, false);
            final GalleryViewHolder galleryViewHolder = new GalleryViewHolder(inflate);
            galleryViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList(PHOTO_LIST, new ArrayList(getCurrentList()));
                    bundle.putInt(PHOTO_POSITION, galleryViewHolder.getAdapterPosition());
                    NavController navController = Navigation.findNavController(v);
                    navController.navigate(R.id.action_galleryFragment_to_photoFragment, bundle);
                }
            });
            return galleryViewHolder;
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.footer_gallery, parent, false);
            final FooterViewHolder footerViewHolder = new FooterViewHolder(view);

            ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).setFullSpan(true);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    footerViewHolder.progressBar.setVisibility(View.VISIBLE);
                    footerViewHolder.tvStatus.setText("正在加载");
                    galleryViewModel.fetchData();
                }
            });

            return footerViewHolder;
        }
    }


    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        if (position == getItemCount() - 1) {
            FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
            switch (footerViewStatus) {
                case GalleryViewModel.DATA_STATUS_CAN_LOAD_MODE:
                    footerViewHolder.progressBar.setVisibility(View.VISIBLE);
                    footerViewHolder.tvStatus.setText("正在加载");
                    footerViewHolder.itemView.setClickable(false);
                    break;
                case GalleryViewModel.DATA_STATUS_NETWORK_ERROR:
                    footerViewHolder.progressBar.setVisibility(View.GONE);
                    footerViewHolder.tvStatus.setText("网络异常，点击重试");
                    footerViewHolder.itemView.setClickable(true);
                    break;
                case GalleryViewModel.DATA_STATUS_NO_MODE:
                    footerViewHolder.progressBar.setVisibility(View.GONE);
                    footerViewHolder.tvStatus.setText("全部加载完毕");
                    footerViewHolder.itemView.setClickable(false);
                    break;
            }
            return;
        }
        final GalleryViewHolder galleryViewHolder = (GalleryViewHolder) holder;
        galleryViewHolder.shimmerLayout.setShimmerAngle(30);
        galleryViewHolder.shimmerLayout.setShimmerColor(0x55ffffff);
        galleryViewHolder.shimmerLayout.startShimmerAnimation();

        Pixabay.PhotoItem item = getItem(position);

        galleryViewHolder.tvUser.setText(item.getPhotoUser());
        galleryViewHolder.tvFavorites.setText(String.valueOf(item.getFavorites()));
        galleryViewHolder.tvLikes.setText(String.valueOf(item.getLikes()));
        galleryViewHolder.imageView.getLayoutParams().height = item.getPhotoHeight();

        Glide.with(holder.itemView)
                .load(item.getPreviewUrl())
                .placeholder(R.drawable.ic_baseline_photo_24)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        Log.d("myTAG", "onLoadFailed: 图片加载失败", e);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        galleryViewHolder.shimmerLayout.stopShimmerAnimation();
                        return false;
                    }
                })
                .into(galleryViewHolder.imageView);
    }

    class GalleryViewHolder extends RecyclerView.ViewHolder {
        public ShimmerLayout shimmerLayout;
        public ImageView imageView;
        public TextView tvUser;
        public TextView tvLikes;
        public TextView tvFavorites;

        public GalleryViewHolder(@NonNull View itemView) {
            super(itemView);
            shimmerLayout = itemView.findViewById(R.id.shimmerLayoutGallery);
            imageView = itemView.findViewById(R.id.imageViewGallery);
            tvUser = itemView.findViewById(R.id.tv_user);
            tvLikes = itemView.findViewById(R.id.tv_likes);
            tvFavorites = itemView.findViewById(R.id.tv_favorites);
        }
    }

    class FooterViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;
        public TextView tvStatus;

        public FooterViewHolder(@NonNull View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progressBar);
            tvStatus = itemView.findViewById(R.id.tv_status);
        }
    }
}
